package top.wugy.blog.routes;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Redis;
import top.wugy.blog.kits.BlogKit;
import top.wugy.blog.kits.Const;
import top.wugy.blog.model.TUser;
import top.wugy.blog.searcher.SearcherKit;

/**
 * wugy on 2017/11/3 13:20
 */
public class FrontController extends BaseController {

    public void index() {
        redirect("/blog/index");
    }

    public void login() {
        String username = getPara("username");
        String password = getPara("password");

        if (StrKit.isBlank(username)) {
            render(Const.ERROR, "用户名不能为空");
            return;
        }
        if (StrKit.isBlank(password)) {
            render(Const.ERROR, "密码不能为空");
            return;
        }
        TUser user = TUser.dao.findByUsername(username);
        if (user == null) {
            render(Const.ERROR, "用户名或密码错误");
            return;
        }
        // 校验密码
        if (!user.getPassword().equals(BlogKit.encodeMD5Hex(password))) {
            render(Const.ERROR, "密码错误");
            return;
        }
        String jwtToken = BlogKit.jwtToken(user.getId());
        setSessionAttr(Const.TOKEN, jwtToken);
        setAttr("isLogin", true);

        Redis.use(Const.REDIS_CACHE).setex(Const.LOGIN_TIME, Const.JWT_EXPIRE, BlogKit.date2Str(BlogKit.now()));
        renderOk(jwtToken);
    }

    public void logout() {
        getSession().invalidate();
        removeSessionAttr(Const.TOKEN);
        Redis.use(Const.REDIS_CACHE).del(Const.LOGIN_TIME);
        renderOk();
    }

    public void timeline() {
        render("/views/timeline.html");
    }

    public void searchBlog() {
        String keyword = getPara("keyword");
        setAttr("blogPage", SearcherKit.search(getPageNum(), Const.DEF_PAGE_SIZE, keyword));
        setAttr("keyword", keyword);
        render("/views/index.html");
    }
}
